package com.hnhuas.salary.modules.admin.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.sax.handler.RowHandler;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hnhuas.salary.common.BaseController;
import com.hnhuas.salary.common.utils.FileHandleUtil;
import com.hnhuas.salary.common.utils.PageUtils;
import com.hnhuas.salary.common.utils.R;
import com.hnhuas.salary.common.validator.ValidatorUtils;
import com.hnhuas.salary.modules.admin.entity.SalaryUserEntity;
import com.hnhuas.salary.modules.admin.service.SalaryUserService;
import com.wangfan.endecrypt.utils.EndecryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.wf.jwtp.annotation.RequiresRoles;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * 系统用户
 *
 * @author weirdor
 * @email 179946422@qq.com
 * @date 2019-08-23 18:52:30
 */
@RestController
@RequestMapping("/admin/user")
public class SalaryUserController extends BaseController {
    @Autowired
    private SalaryUserService salaryUserService;


    /***
     *
     * @param file
     * @param request
     * @param response
     * @return
     */
    @PostMapping("upload")
    public R ImportExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request,
                         HttpServletResponse response) {
        if (file.isEmpty()) {
            return R.error(404, "文件不存在");
        }
        try {
//            String path = FileHandleUtil.upload(file.getInputStream(), "/", file.getOriginalFilename());

            String originalFileName = file.getOriginalFilename();
            String suffix = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
            File outFile;
            String path;
            path = getDate() + UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
            outFile = new File(File.listRoots()[0], "/upload/" + path);
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }
            file.transferTo(outFile);
            ExcelUtil.read07BySax("/upload/" +path, 3, createRowHandler());

            return R.ok();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();

    }


    private RowHandler createRowHandler() {
        return new RowHandler() {
            @Override
            public void handle(int sheetIndex, int rowIndex, List<Object> rowlist) {

                String name = Convert.toStr(rowlist.get(2));
                String idCard = Convert.toStr(rowlist.get(3));
                //新建人员信息
                SalaryUserEntity userEntity = new SalaryUserEntity();
                //判断人员是否存在
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("name", name);
                queryWrapper.eq("identity_card", idCard);
                Integer count = salaryUserService.count(queryWrapper);
                idCard=idCard.toLowerCase();
                idCard = idCard.substring(idCard.length()-6);
                String digestHex =  EndecryptUtils.encrytMd5(idCard);
                if (count == 0) {
                    userEntity.setIdentityCard(Convert.toStr(rowlist.get(3)));
                    userEntity.setName(name);
                    userEntity.setIsAdmin(false);
                    userEntity.setPassword(digestHex);
                    salaryUserService.save(userEntity);
                }

            }
        };
    }

    /**
     * 所有用户列表
     */
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = salaryUserService.queryPage(params);
        return R.ok().put("data", page);
    }


    @PutMapping("/psw/{id}")
    public R resetPsw(@PathVariable("id") Long userId) {
        SalaryUserEntity user = new SalaryUserEntity();
        user.setId(userId);
        user.setPassword(EndecryptUtils.encrytMd5("123456"));
        if (salaryUserService.updateById(user)) {
            return R.ok("重置密码成功");
        }
        return R.error("重置密码失败");
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @RequiresRoles("admin")
    public R info(@PathVariable("id") Long id){
        SalaryUserEntity salaryUser = salaryUserService.getById(id);

        return R.ok().put("salaryUser", salaryUser);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @RequiresRoles("admin")
    public R save(@RequestBody SalaryUserEntity salaryUser){
        String idCard=salaryUser.getIdentityCard();
        idCard=idCard.toLowerCase();
        String digestHex;
        if (salaryUser.getIsAdmin()){
            digestHex =  EndecryptUtils.encrytMd5(salaryUser.getPassword());
            salaryUser.setPassword(digestHex);
        }else{
            idCard = idCard.substring(idCard.length()-6);
            digestHex =  EndecryptUtils.encrytMd5(idCard);
            salaryUser.setPassword(digestHex);
        }
        salaryUserService.save(salaryUser);
        return R.ok();
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    @RequiresRoles("admin")
    public R update(@RequestBody SalaryUserEntity salaryUser){
        ValidatorUtils.validateEntity(salaryUser);

        if (!StringUtils.isEmpty(salaryUser.getPassword())){
            String idCard=salaryUser.getIdentityCard();
            idCard=idCard.toLowerCase();
            idCard = idCard.substring(idCard.length()-6);
            String digestHex =  EndecryptUtils.encrytMd5(idCard);
            salaryUser.setPassword(digestHex);
        }
        salaryUserService.updateById(salaryUser);

        return R.ok();
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{id}")
    @RequiresRoles("admin")
    public R delete(@PathVariable("id") Long id){
        salaryUserService.removeById(id);

        return R.ok();
    }

    // 获取当前日期
    private String getDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        return sdf.format(new Date());
    }
}
